package org.darcy.framework.util;

import java.util.UUID;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.darcy.entity.SysUser;
import org.darcy.framework.blog.holder.RequestHolder;

/**
 * Session工具类
 */
public class SessionUtil {
	
	public static final String KAPTCHA_SESSION_KEY = "KAPTCHA";

	/**
	 * 当前是否登录
	 *
	 * @return
	 */
	public static boolean isLogin() {
		return null != SessionUtil.getUser();
	}

	/**
	 * 获取session中的用户信息
	 *
	 * @return User
	 */
	public static SysUser getUser() {
		Subject sub = SecurityUtils.getSubject();
		if (sub.isAuthenticated()) {
			SysUser user = (SysUser) sub.getPrincipal();
			return user;
		}
		return null;
	}
	
	/**
	 * 获取普通用户的用户id
	 */
	public static Long getCommonUserId() {
		Subject sub = SecurityUtils.getSubject();
		if (sub.isAuthenticated()) {
			SysUser user = (SysUser) sub.getPrincipal();
			if(sub.hasRole("role:user")) {
				return user.getId();				
			}
		}		
		return null;
	}

	/**
	 * 添加session
	 *
	 * @param user
	 */
	public static void setUser(SysUser user) {
		RequestHolder.setSession("user", user);
	}

	/**
	 * 删除session信息
	 */
	public static void removeUser() {
		RequestHolder.removeSession("user");
	}

	/**
	 * 获取session中的Token信息
	 *
	 * @return String
	 */
	public static String getToken(String key) {
		return (String) RequestHolder.getSession(key);
	}

	/**
	 * 添加Token
	 */
	public static void setToken(String key) {
		RequestHolder.setSession(key, UUID.randomUUID().toString());
	}

	/**
	 * 删除Token信息
	 */
	public static void removeToken(String key) {
		RequestHolder.removeSession(key);
	}

	/**
	 * 获取验证码
	 */
	public static String getKaptcha() {
		return (String) RequestHolder.getSession(KAPTCHA_SESSION_KEY);
	}

	/**
	 * 保存验证码
	 */
	public static void setKaptcha(String kaptcha) {
		RequestHolder.setSession(KAPTCHA_SESSION_KEY, kaptcha);
	}

	/**
	 * 删除验证码
	 */
	public static void removeKaptcha() {
		RequestHolder.removeSession(KAPTCHA_SESSION_KEY);
	}

	/**
	 * 删除所有的session信息
	 */
	public static void removeAllSession() {
		String[] keys = RequestHolder.getSessionKeys();
		if (keys != null && keys.length > 0) {
			for (String key : keys) {
				RequestHolder.removeSession(key);
			}
		}
	}
}
